package com.zxl.yjb.activity.home.position;

import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdate;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptor;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.zxl.yjb.R;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.LocationBean;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.PoiItemExt;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.utils.LogUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PositionActivity extends BaseActivity {

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.iv_location)
    ImageView iv_location;
    @BindView(R.id.tv_page_title)
    TextView tv_page_title;
    @BindView(R.id.tv_sub_title)
    TextView tv_sub_title;
    @BindView(R.id.rl_often_position)
    RelativeLayout rl_often_position;
    @BindView(R.id.tv_ok)
    TextView tv_ok;
    @BindView(R.id.map_view)
    MapView map_view;

    private double lng;
    private double lat;

    private DataManager dataManager;

    private AMap aMap;
    private MyLocationStyle myLocationStyle;
    private LatLng centerPosition;
    private GeocodeSearch geocoderSearch;
    private LatLonPoint latLonPoint;

    private Marker mMarker;
    private BitmapDescriptor mBitmapDescriptor;
    private MarkerOptions markerOptions;

    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;// POI搜索
    private ArrayList<PoiItem> poiItemList = new ArrayList<>();
    private PoiItem poiItem;

    private String origin = "";
    private LoginSucessBean loginSucessBean;
    private LocationBean locationBean;

    private ArrayList<PoiItemExt> historyPoiItemList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_position);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        loginSucessBean = (LoginSucessBean) SaveBeanUtil.getBean(PositionActivity.this, Const.VIPINFO);
        locationBean = (LocationBean) SaveBeanUtil.getBean(PositionActivity.this, Const.LOCATION_LNGLAT);
        historyPoiItemList = (ArrayList<PoiItemExt>) SaveBeanUtil.getBean(PositionActivity.this, Const.POSITION_HISTORY);
        origin = getIntent().getStringExtra("origin");
        if (origin == null)
        {
            iv_location.setVisibility(View.VISIBLE);
            origin = "";
        }

        initView();
        initMap(savedInstanceState);

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        map_view.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        map_view.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map_view.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        map_view.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    protected void initView() {

        if ("MessagePublishActivity".equals(origin)||"OrderCreateActivity".equals(origin)||"MessageListActivity".equals(origin))
        {
            tv_page_title.setText("选择位置");
            tv_sub_title.setText("选择常用位置");
        }
        else
        {
            tv_page_title.setText("选择接单位置");
        }

        iv_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (locationBean!=null)
                {
                    String latitude = locationBean.getLat()+"";
                    String longitude = locationBean.getLng()+"";
                    if ("".equals(origin)
                            &&!TextUtils.isEmpty(latitude)
                            &&!TextUtils.isEmpty(longitude)
                            &&!"null".equals(latitude)
                            &&!"null".equals(longitude)){
                        aMap.setMyLocationEnabled(false);
                        LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                        /*MarkerOptions markerOptions = (new MarkerOptions()).position(latLng).icon(this.mBitmapDescriptor);*/
//                        aMap.addMarker(markerOptions);
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 0, 0));
                        aMap.moveCamera(cameraUpdate);
                    }
                }

            }
        });
    }


    private void initMap(Bundle savedInstanceState) {
        map_view.onCreate(savedInstanceState);// 此方法必须重写
        aMap = map_view.getMap();

        myLocationStyle = new MyLocationStyle();
        myLocationStyle.interval(2000);
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
                centerPosition = new LatLng(location.getLatitude(),location.getLongitude());
            }
        });
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {
                centerPosition = cameraPosition.target;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                centerPosition = cameraPosition.target;
//                getAddress(centerPosition);
                getSearchPosition(centerPosition);

            }
        });
        aMap.setOnMyLocationChangeListener(new AMap.OnMyLocationChangeListener() {
            @Override
            public void onMyLocationChange(Location location) {
//                getAddress(new LatLng(location.getLatitude(),location.getLongitude()));
                getSearchPosition(new LatLng(location.getLatitude(),location.getLongitude()));
//                addLocatedMarker(new LatLng(location.getLatitude(),location.getLongitude()),"");
            }
        });




        geocoderSearch = new GeocodeSearch(this);
        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
                addLocatedMarker(centerPosition,regeocodeResult.getRegeocodeAddress().getFormatAddress(),"");
            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }
        });

        initSearchPotision();

        markerOptions = new MarkerOptions();
        mBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.zy_dtdw);
        markerOptions.icon(this.mBitmapDescriptor);
        markerOptions.snippet("");

        if (loginSucessBean!=null)
        {
            String latitude = loginSucessBean.getLatitude()+"";
            String longitude = loginSucessBean.getLongitude()+"";
            if ("".equals(origin)
                    &&!TextUtils.isEmpty(latitude)
                    &&!TextUtils.isEmpty(longitude)
                    &&!"null".equals(latitude)
                    &&!"null".equals(longitude)){
                aMap.setMyLocationEnabled(false);
                LatLng latLng = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
                /*MarkerOptions markerOptions = (new MarkerOptions()).position(latLng).icon(this.mBitmapDescriptor);*/
                aMap.addMarker(markerOptions);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 15, 0, 0));
                aMap.moveCamera(cameraUpdate);
            }
            else
            {
                iv_location.setVisibility(View.GONE);
                aMap.setMyLocationEnabled(true);
            }
        }

    }


    private void sendPosition()
    {
        dataManager = new DataManager();
        Map<String,String> map = new HashMap<>();
        map.put("lon",centerPosition.longitude+"");
        map.put("lat",centerPosition.latitude+"");
        ObserverOnNextListener<String> listener = new ObserverOnNextListener<String>() {
            @Override
            public void onNext(String s) {
                ToastUtils.show(PositionActivity.this,"位置设置成功");
                EventBus.getDefault().post(new MessageEvent("refreshUserInfo"));
                finish();
            }
        };
        dataManager.reglocation(new ProgressObserver<String>(listener,this),map);
    }

    private void addLocatedMarker(LatLng latLng,String title,String snippet) {
        if (mMarker!=null)
            mMarker.remove();
        if (!TextUtils.isEmpty(title))
            markerOptions.title(title);
            markerOptions.snippet(snippet);
        markerOptions.position(latLng).icon(this.mBitmapDescriptor);
        mMarker = aMap.addMarker(markerOptions);
        mMarker.setPositionByPixels(this.map_view.getWidth() / 2, this.map_view.getHeight() / 2);
        if (!TextUtils.isEmpty(title))
            mMarker.showInfoWindow();
        else
            mMarker.hideInfoWindow();
    }


    private void initSearchPotision()
    {
        query = new PoiSearch.Query("", "", "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(10);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页
        query.setCityLimit(true);
        poiSearch = new PoiSearch(this, query);
    }

    private void getSearchPosition(final LatLng latLng) {
        latLonPoint = new LatLonPoint(latLng.latitude,latLng.longitude);
        poiSearch.setBound(new PoiSearch.SearchBound(latLonPoint, 5000, true));
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
//                poiItemList.addAll(poiResult.getPois());
                poiItem = poiResult.getPois().get(0);
                LatLonPoint latLonPoint = poiItem.getLatLonPoint();
                addLocatedMarker(new LatLng(latLonPoint.getLatitude(),latLonPoint.getLongitude()),poiItem.getTitle(),poiItem.getSnippet());
            }

            @Override
            public void onPoiItemSearched(PoiItem poiItem, int i) {
                LogUtil.e("aa", "aa");
            }
        });
        poiSearch.searchPOIAsyn();
    }


    private void saveHisPotision(PoiItem poiItem) {
        if (historyPoiItemList == null)
            historyPoiItemList = new ArrayList<>();
        if (historyPoiItemList.size() >= 20) {
            historyPoiItemList.remove(historyPoiItemList.size() - 1);
        }
        PoiItemExt poiItemExt = new PoiItemExt(poiItem.getPoiId(), poiItem.getTitle(), poiItem.getSnippet(), poiItem.getLatLonPoint().getLongitude(), poiItem.getLatLonPoint().getLatitude());
        for (int i = 0; i < historyPoiItemList.size(); i++) {
            if (historyPoiItemList.get(i).getId().equals(poiItem.getPoiId()))
                return;
        }
        historyPoiItemList.add(0, poiItemExt);
        SaveBeanUtil.putBean(PositionActivity.this, Const.POSITION_HISTORY, historyPoiItemList);
    }


    @OnClick({R.id.iv_back, R.id.rl_often_position, R.id.tv_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_often_position:
                Intent intent = new Intent(PositionActivity.this,PositionSelectActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_ok:
                if("MessagePublishActivity".equals(origin)||"OrderCreateActivity".equals(origin)||"MessageListActivity".equals(origin))
                {
                    saveHisPotision(poiItem);
                    Intent intent1 = new Intent();
                    intent1.putExtra("position",poiItem);
                    setResult(RESULT_OK,intent1);
                    finish();
                }
                else
                {
                    sendPosition();
                }
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent)
    {
        if ("position".equals(messageEvent.getMessage()))
        {
            try {
                LatLng latLng = (LatLng) messageEvent.getObject();
                getSearchPosition(latLng);
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
            } catch (Exception e) {

            }
        }
    }
}
